<!-- HomePage.vue -->
<template>
  <div class="home-content" >
    <div v-if="loading" class="loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <div v-else-if="error" class="error">
      <el-icon><Warning /></el-icon>
      <span>{{ error }}</span>
    </div>
    <div v-else class="content-wrapper">
      <!-- Hero Banner Section -->
      <div class="hero-banner">
        <div class="banner-content">
          <h1 class="banner-title">发现精选好物</h1>
          <p class="banner-subtitle">品质生活，从这里开始</p>
        </div>
      </div>

      <!-- Promotional Cards -->
      <div class="section">
        <h2 class="section-title">
          <el-icon><Star /></el-icon>
          热门活动
        </h2>
        <div class="promo-cards">
          <div 
            v-for="promotionType in fixedPromotions" 
            :key="promotionType.id" 
            class="promo-card"
            @click="viewPromotionList(promotionType.id)"
          >
            <div class="promo-icon">{{ promotionType.icon }}</div>
            <h3 class="promo-title">{{ promotionType.name }}</h3>
            <p class="promo-description">{{ promotionType.description }}</p>
            <div class="promo-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- Category and Product Display -->
      <div class="section">
        <h2 class="section-title">
          <el-icon><Grid /></el-icon>
          商品分类
        </h2>
        <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange" class="category-tabs">
          <el-tab-pane
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :name="category.id.toString()"
          >
            <div class="products-container">
              <div class="product-grid" v-if="products[category.id]?.list && products[category.id].list.length > 0">
                <div 
                  v-for="product in products[category.id].list" 
                  :key="product.id" 
                  class="product-card"
                  @click="viewProduct(product.id)"
                >
                  <div class="product-image-container">
                    <img :src="product.mainImage" class="product-image" alt="商品图片" />
                    <div class="product-overlay">
                      <el-button type="primary" size="small" round>
                        <el-icon><View /></el-icon>
                        查看详情
                      </el-button>
                    </div>
                  </div>
                  <div class="product-info">
                    <h3 class="product-title">{{ product.title }}</h3>
                    <div class="product-price">
                      <span class="current-price">￥{{ product.price }}</span>
                      <span class="original-price" v-if="product.originalPrice">￥{{ product.originalPrice }}</span>
                    </div>
                    <div class="product-tags" v-if="product.tags">
                      <el-tag v-for="tag in product.tags" :key="tag" size="small">{{ tag }}</el-tag>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="empty-state">
                <el-icon class="empty-icon"><Box /></el-icon>
                <p>该分类暂无商品</p>
              </div>
              
              <!-- Pagination -->
              <div class="pagination-wrapper" v-if="products[category.id]?.total > 0">
                <el-pagination
                  v-model:current-page="products[category.id].currentPage"
                  v-model:page-size="products[category.id].pageSize"
                  :total="products[category.id].total"
                  :page-sizes="[8, 16, 24, 32]"
                  layout="total, sizes, prev, pager, next"
                  background
                  @size-change="size => handlePageSizeChange(category.id, size)"
                  @current-change="page => handlePageChange(category.id, page)"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { getTaskCategory, getProduct, getProductWithSku } from '../api/product';
import { Loading, Warning, Star, ArrowRight, Grid, View, Box } from '@element-plus/icons-vue';

const router = useRouter();
const loading = ref(false);
const error = ref(null);
const activeCategory = ref('1');
const categories = ref([]);
// 将 products 初始化为一个 Proxy 对象，确保响应式
const products = ref({});
const fixedPromotions = ref([
  { id: 1, name: '秒杀', description: '限时抢购，超低折扣', icon: '⚡' },
  { id: 2, name: '团购', description: '组团购买，享受优惠', icon: '👥' },
  { id: 3, name: '满减', description: '满额即减，优惠多多', icon: '💰' },
  { id: 4, name: '套餐', description: '组合套餐，省心省钱', icon: '📦' }
]);

const fetchCategories = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await getTaskCategory();
    console.log('getTaskCategory response:', response);
    if (response.data.code === "0" || response.data.code === "200") {
      categories.value = response.data.data;
      if (categories.value.length > 0) {
        activeCategory.value = categories.value[0].id.toString();
        // 确保在获取分类后，立即为第一个分类初始化产品数据
        await fetchProducts(categories.value[0].id, 1, 8);
      }
    } else {
      error.value = response.message || '获取分类失败';
      ElMessage.error(error.value);
    }
  } catch (err) {
    error.value = '获取分类失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const fetchProducts = async (categoryId, page = 1, size = 8) => {
  // 在请求前，先确保该分类的数据结构已存在，避免 v-if 判断出错
  if (!products.value[categoryId]) {
    products.value[categoryId] = { list: [], total: 0, currentPage: page, pageSize: size };
  }

  // 可以选择在这里也显示一个加载状态，或者只在外层控制
  // loading.value = true; // 如果需要每个tab独立加载提示

  try {
    const response = await getProduct(categoryId, page, size);
    console.log('getProduct response:', response);
    if (response.data.code === "0" || response.data.code === "200") {
      products.value[categoryId] = {
        list: response.data.data.list || [],
        total: response.data.data.list.length || 0, // 确保这里使用后端返回的总数，而不是列表长度
        currentPage: page,
        pageSize: size,
      };
    } else {
      ElMessage.error(response.message || '获取商品失败');
      // 失败时也确保数据结构存在且为空
      products.value[categoryId] = { list: [], total: 0, currentPage: page, pageSize: size };
    }
  } catch (err) { // 捕捉网络错误等
    ElMessage.error('获取商品失败');
    products.value[categoryId] = { list: [], total: 0, currentPage: page, pageSize: size };
  } finally {
    // loading.value = false; // 如果需要每个tab独立加载提示
  }
};

const handleCategoryChange = async (tab) => {
  const categoryId = Number(tab.props.name); // 从 tab 对象获取 name
  if (categoryId && activeCategory.value !== 'search') { // 确保是有效的分类ID
    // 每次切换分类时，重新获取该分类的第一页数据，并保持当前页大小，如果之前没有则默认8
    await fetchProducts(categoryId, 1, products.value[categoryId]?.pageSize || 8);
  }
};

const handlePageChange = async (categoryId, page) => {
  await fetchProducts(categoryId, page, products.value[categoryId].pageSize);
};

const handlePageSizeChange = async (categoryId, size) => {
  products.value[categoryId].currentPage = 1; // 页码重置为1
  await fetchProducts(categoryId, 1, size);
};

const viewProduct = async (productId) => {
  if (!productId) {
    ElMessage.error('商品 ID 缺失');
    return;
  }
  try {
    const res = await getProductWithSku(productId);
    if (res.data.code == 200 || res.data.code == '200') {
      router.push({ name: 'ProductDetail', params: { id: productId } });
    } else {
      ElMessage.error(res.data.message || '商品不存在');
    }
  } catch (error) {
    console.error('获取商品详情失败:', error); // 打印详细错误
    ElMessage.error('获取商品详情失败');
  }
};

const viewPromotionList = (promotionTypeId) => {
  router.push({ name: 'PromotionList', params: { typeId: promotionTypeId } });
};

onMounted(async () => {
  await fetchCategories();
});
</script>

<style scoped>
/* HomePage.vue Styles */

/* Base & Layout */
.home-content {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40px 0;
}

.content-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

/* --- Hero Banner Section --- */
.hero-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  padding: 80px 40px;
  margin-bottom: 60px;
  text-align: center;
  color: white;
  position: relative;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.hero-banner::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="20" cy="20" r="3" fill="white" opacity="0.05"/><circle cx="80" cy="80" r="2" fill="white" opacity="0.07"/><circle cx="50" cy="90" r="4" fill="white" opacity="0.03"/></svg>') repeat;
  animation: float 25s linear infinite;
}

@keyframes float {
  0% { transform: translate(0, 0) rotate(0deg); }
  100% { transform: translate(-30px, -30px) rotate(360deg); }
}

.banner-content {
  position: relative;
  z-index: 1;
}

.banner-title {
  font-size: 4rem;
  font-weight: 800;
  margin-bottom: 20px;
  text-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
  letter-spacing: 1px;
}

.banner-subtitle {
  font-size: 1.5rem;
  opacity: 0.95;
  font-weight: 300;
}

/* --- Section Styling --- */
.section {
  margin-bottom: 60px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 2.2rem;
  font-weight: 700;
  margin-bottom: 35px;
  color: #2c3e50;
  gap: 15px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.section-title .el-icon {
  font-size: 2rem;
  color: #409eff;
}

/* --- Promotional Cards --- */
.promo-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 30px;
  margin-bottom: 30px;
}

.promo-card {
  background: white;
  border-radius: 20px;
  padding: 35px 28px;
  text-align: center;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: all 0.5s cubic-bezier(0.2, 0.8, 0.2, 1);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 1px solid #f0f0f0;
}

.promo-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -120%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(64, 158, 255, 0.15), transparent);
  transition: left 0.6s ease-out;
  z-index: 0;
}

.promo-card:hover::before {
  left: 120%;
}

.promo-card:hover {
  transform: translateY(-12px) scale(1.03);
  box-shadow: 0 20px 50px rgba(64, 158, 255, 0.25);
  border-color: #409eff;
}

.promo-icon {
  font-size: 3.5rem;
  margin-bottom: 20px;
  display: block;
  line-height: 1;
}

.promo-title {
  font-size: 1.6rem;
  font-weight: 700;
  margin-bottom: 15px;
  color: #34495e;
}

.promo-description {
  font-size: 1rem;
  color: #7f8c8d;
  line-height: 1.8;
  margin-bottom: 20px;
}

.promo-arrow {
  color: #409eff;
  font-size: 1.4rem;
  transition: transform 0.3s ease-out;
}

.promo-card:hover .promo-arrow {
  transform: translateX(8px);
}

/* --- Category Tabs --- */
.category-tabs {
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.category-tabs :deep(.el-tabs__header) {
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.category-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.category-tabs :deep(.el-tabs__item) {
  padding: 14px 28px;
  font-weight: 600;
  border-radius: 10px;
  margin-right: 12px;
  transition: all 0.4s ease;
  color: #555;
}

.category-tabs :deep(.el-tabs__item.is-active) {
  background: #409eff;
  color: white;
  box-shadow: 0 4px 15px rgba(64, 158, 255, 0.3);
}

.category-tabs :deep(.el-tabs__active-bar) {
  display: none;
}

/* --- Products Grid --- */
.products-container {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* 缩小卡片最小宽度 */
  gap: 16px; /* 减小卡片之间的间距 */
  margin-bottom: 30px; /* 相应调整下外边距 */
}

.product-card {
  background: white;
  border-radius: 12px; /* 稍微减小圆角 */
  overflow: hidden;
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.06); /* 减小阴影效果 */
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  cursor: pointer;
  position: relative;
  border: 1px solid #f0f0f0;
}

.product-card:hover {
  transform: translateY(-5px); /* 减小悬浮时的上移距离 */
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.1); /* 减小悬浮时的阴影 */
  border-color: #409eff;
}

.product-image-container {
  position: relative;
  overflow: hidden;
  height: 140px; /* **进一步减小图片容器高度** */
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.4s ease;
}

.product-card:hover .product-image {
  transform: scale(1.03); /* 减小悬浮时图片的放大比例 */
}

.product-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.65);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-card:hover .product-overlay {
  opacity: 1;
}

.product-overlay .el-button {
  min-width: 80px; /* 进一步减小按钮最小宽度 */
  padding: 6px 12px; /* 进一步减小按钮内边距 */
  font-size: 0.8rem; /* 进一步减小按钮字体大小 */
}

.product-info {
  padding: 1px; /* **关键：进一步减小信息区域内边距** */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 40px; /* **关键：减小信息区域的最小高度** */
}

.product-title {
  font-size: 0.9rem; /* **关键：进一步减小标题字体大小** */
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px; /* 进一步减小标题下外边距 */
  line-height: 1.3; /* 调整行高 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  display: flex;
  align-items: baseline;
  gap: 4px; /* 进一步减小价格之间的间距 */
  margin-top: auto;
  margin-bottom: 6px; /* 进一步减小价格下外边距 */
}

.current-price {
  font-size: 1rem; /* **关键：进一步减小当前价格字体大小** */
  font-weight: 700;
  color: #e74c3c;
}

.original-price {
  font-size: 0.7rem; /* **关键：进一步减小原价格字体大小** */
  color: #95a5a6;
  text-decoration: line-through;
}

.product-tags {
  display: flex;
  gap: 3px; /* 进一步减小标签间距 */
  flex-wrap: wrap;
  justify-content: flex-start; /* 标签左对齐 */
}

.product-tags .el-tag {
  border-radius: 6px; /* 进一步减小标签圆角 */
  font-size: 0.6rem; /* **关键：进一步减小标签字体大小** */
  padding: 1px 5px; /* 进一步减小标签内边距 */
  height: auto;
}

/* --- Empty State --- */
.empty-state {
  text-align: center;
  padding: 50px 15px;
  color: #95a5a6;
  font-size: 1.1rem;
  background-color: white;
  border-radius: 16px;
  margin-top: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 15px;
  color: #bdc3c7;
}

/* --- Pagination --- */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 15px 0;
}

.pagination-wrapper :deep(.el-pagination) {
  background: white;
  padding: 15px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.06);
}

.pagination-wrapper :deep(.el-pager li) {
  border-radius: 8px;
}

.pagination-wrapper :deep(.el-pager li.is-active) {
  background-color: #409eff !important;
  color: white !important;
}

/* Loading & Error States */
.loading, .error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 500px;
  gap: 20px;
  font-size: 1.3rem;
  color: #7f8c8d;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 20px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.05);
}

.loading .el-icon {
  font-size: 3rem;
  color: #409eff;
}

.error .el-icon {
  font-size: 3rem;
  color: #e74c3c;
}

/* --- Responsive Design --- */
@media (max-width: 992px) {
  .hero-banner {
    padding: 60px 30px;
  }
  .banner-title {
    font-size: 3rem;
  }
  .banner-subtitle {
    font-size: 1.3rem;
  }
  .promo-cards {
    grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    gap: 20px;
  }
  .section-title {
    font-size: 1.9rem;
  }

  /* Products */
  .product-grid {
    grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); /* 进一步缩小最小宽度 */
    gap: 12px;
  }
  .product-image-container {
    height: 120px; /* 调整图片高度 */
  }
  .product-info {
    min-height: 70px; /* 调整信息区域最小高度 */
    padding: 8px; /* 调整内边距 */
  }
  .product-title {
    font-size: 0.85rem;
  }
  .current-price {
    font-size: 0.95rem;
  }
  .original-price {
    font-size: 0.65rem;
  }
  .product-tags .el-tag {
    font-size: 0.55rem;
    padding: 1px 4px;
  }
  .product-overlay .el-button {
    min-width: 70px;
    padding: 5px 10px;
    font-size: 0.75rem;
  }
}

@media (max-width: 768px) {
  .content-wrapper {
    padding: 0 16px;
  }
  
  .hero-banner {
    padding: 50px 24px;
    margin-bottom: 30px;
  }
  
  .banner-title {
    font-size: 2.5rem;
  }
  
  .banner-subtitle {
    font-size: 1.1rem;
  }
  
  .promo-cards {
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 16px;
  }
  
  .section {
    margin-bottom: 30px;
  }
  
  .section-title {
    font-size: 1.6rem;
    gap: 10px;
  }
  .section-title .el-icon {
    font-size: 1.8rem;
  }

  .promo-card {
    padding: 28px 20px;
  }
  .promo-icon {
    font-size: 2.8rem;
  }
  .promo-title {
    font-size: 1.3rem;
  }

  /* Products */
  .product-grid {
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); /* 更小屏幕下继续缩小 */
    gap: 8px;
  }
  .product-image-container {
    height: 100px;
  }
  .product-info {
    padding: 6px; /* 进一步缩小内边距 */
    min-height: 60px; /* 进一步缩小最小高度 */
  }
  .product-title {
    font-size: 0.8rem;
  }
  .current-price {
    font-size: 0.9rem;
  }
  .original-price {
    font-size: 0.6rem;
  }
  .product-tags .el-tag {
    font-size: 0.5rem;
    padding: 1px 3px;
  }

  .empty-state {
    padding: 50px 15px;
    font-size: 1rem;
  }
  .empty-icon {
    font-size: 4rem;
  }

  .category-tabs {
    padding: 15px;
  }
  .category-tabs :deep(.el-tabs__item) {
    padding: 10px 18px;
    font-size: 0.9rem;
  }
}

@media (max-width: 480px) {
  .hero-banner {
    padding: 30px 15px;
  }
  .banner-title {
    font-size: 1.8rem;
  }
  .banner-subtitle {
    font-size: 1rem;
  }
  .promo-cards {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  .section-title {
    font-size: 1.4rem;
    flex-direction: column;
    text-align: center;
  }
  .section-title .el-icon {
    font-size: 1.6rem;
  }
  .promo-card {
    padding: 20px;
  }

  /* Products */
  .product-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  .product-image-container {
    height: 120px; /* 单列时可稍微增加图片高度 */
  }
  .product-info {
    padding: 10px;
    min-height: auto;
  }
  .product-title {
    font-size: 0.9rem;
  }
  .current-price {
    font-size: 1rem;
  }

  .pagination-wrapper :deep(.el-pagination) {
    padding: 12px 18px;
  }
}
</style>